package org.luckyjourney.controller.wx;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.luckyjourney.entity.dto.UserWXLoginDTO;
import org.luckyjourney.entity.user.User;
import org.luckyjourney.entity.user.dto.UserDTO;
import org.luckyjourney.entity.vo.RegisterVO;
import org.luckyjourney.entity.vo.UserWXLoginVO;
import org.luckyjourney.exception.BaseException;
import org.luckyjourney.service.LoginService;
import org.luckyjourney.service.user.UserRoleService;
import org.luckyjourney.service.user.UserService;
import org.luckyjourney.util.JwtUtils;
import org.luckyjourney.util.R;
import org.luckyjourney.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/luckyjourney/regular/miniprograms")
@Api(tags = "微信小程序登录")
@Slf4j
public class UserWxController {

    @Autowired
    LoginService loginService;
    @Autowired
    UserRoleService userRoleService;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @PostMapping("/wx")
    @ApiOperation("微信小程序登录")
    public Result wxLogin(@RequestBody UserWXLoginDTO userWXLoginDTO){
      User  user = loginService.wxLogin(userWXLoginDTO);
        List<String> roleName =userRoleService.selectRoleName(user.getId());
        for (String role : roleName) {
            if (!role.equals("普通用户")) {
                throw new BaseException("该账户没有权限登录");
            }
        }
        String phone = user.getPhone();
        if(ObjectUtil.isEmpty(phone)){
            UserWXLoginVO userWXLoginVO=UserWXLoginVO.builder()
                    .openid(user.getOpenid())
                    .phone(user.getPhone())
                    .status(false)
                    .build();
            return Result.success(userWXLoginVO);
        }
        UserWXLoginVO userWXLoginVO=UserWXLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .status(true)
                .phone(user.getPhone())
                .build();
        return Result.success(userWXLoginVO);
    }


    @PostMapping("/WxPhone")
    @ApiOperation("小程序端获取手机号")
    public R WXPhone(@RequestBody  UserDTO userDTO) throws Exception {
        String phone = loginService.WXPhone(userDTO);
        return R.ok().data(phone);
    }

    @PostMapping("/WxPhoneLogin")
    @ApiOperation("小程序端手机号登录")
    public R WXPhoneLogin(@RequestBody  UserDTO userDTO) throws Exception {
        User user = loginService.WXPhoneLogin(userDTO);
        List<String> roleName =userRoleService.selectRoleName(user.getId());
        if (ObjectUtil.isEmpty(roleName)){
            throw new BaseException("该账户没没有角色");
        }
        for (String role : roleName) {
            if (!role.equals("普通用户")) {
                throw new BaseException("该账户没有权限登录");
            }
        }
        // 登录成功，生成token
        String token = JwtUtils.getJwtToken(user.getId(), user.getNickName());
        final HashMap<Object, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("name",user.getNickName());
        return R.ok().data(map);
    }


    /**
     * 手机号注册并登录
     * @param
     * @return
     */
    @PostMapping("/phoneLogin")
    @ApiOperation("注册登录接口")
    public R phoneLogin(@RequestBody  UserDTO userDTO) throws Exception {
        if (ObjectUtil.isEmpty(userDTO.getOpencode())){
            return R.error().message("opencode不能为空");
        }
        String phone = loginService.WXPhone(userDTO);
        redisTemplate.opsForValue().set(phone,userDTO.getOpencode());
        //查询user表中是否有phone的对象
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,phone);
        User user = userService.getOne(wrapper);
        if (ObjectUtil.isEmpty(user)){
            //不存在就去注册
            RegisterVO registerVO = new RegisterVO();
            registerVO.setPhone(phone);
            registerVO.setPassword("123456");
            registerVO.setCode(userDTO.getOpencode());
            registerVO.setModuleId(userDTO.getModuleId());
            registerVO.setOpenid(userDTO.getOpenid());
            userService.register(registerVO);
        }
        User user1 = userService.getOne(wrapper);
        // 登录成功，生成token
        String token = JwtUtils.getJwtToken(user1.getId(), user1.getNickName());
        final HashMap<Object, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("name",user1.getNickName());
        return R.ok().data(map);
    }


}
